package com.lwm.transactional.xml.utils;

import java.sql.Connection;
import java.sql.SQLException;

/**
 * 事务管理相关 开启事务、提交事务、回滚事务、释放连接
 *
 * @author liweimin
 * @date 2021/6/10 16:15
 * @since
 */
public class TransactionManager {

    private ConnectionUtils connectionUtils;

    public TransactionManager() {
    }

    public TransactionManager(ConnectionUtils connectionUtils) {
        this.connectionUtils = connectionUtils;
    }

    /**
     * 开启事务
     */
    public void start() {
        try {
            connectionUtils.getConnection().setAutoCommit(false);
        } catch (SQLException throwable) {
            throwable.printStackTrace();
        }
    }

    /**
     * 提交事务
     */
    public void commit() {
        try {
            connectionUtils.getConnection().commit();
        } catch (SQLException throwable) {
            throwable.printStackTrace();
        }
    }

    /**
     * 回滚事务
     */
    public void rollback() {
        try {
            Connection connection = connectionUtils.getConnection();
            connection.rollback();
        } catch (SQLException throwable) {
            System.out.println("事务回滚异常");
            throwable.printStackTrace();
        }
    }

    /**
     * 释放连接
     */
    public void release() {
        try {
            connectionUtils.getConnection().close();//还回连接池
            connectionUtils.removeConnection();
        } catch (SQLException throwable) {
            throwable.printStackTrace();
        }
    }
}
